// var powerlist = ["/micro/ident-group:queryList","/micro/ident-group:add"];
<!--自定义函数判断权限-->
var userInfo = getAuthority();
var powerlist = JSON.parse(userInfo).permissions;
/*自定义函数判断权限*/
template.defaults.imports.hasPower = function(data){
    if(powerlist.includes(data)){
        return true;
    }
    return false;
};


layui.use(['layer', 'form', 'table', 'util', 'dtree','admin','laypage'], function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;
    var util = layui.util;
    var dtree = layui.dtree;
    var admin = layui.admin;
    var laypage = layui.laypage;
    var Authorization;//请求接口用
    var count = 0;//总个数
    var current=1;//当前页
    var fistRenderPage= true;//是否第一次渲染分页
    var first_renderTree = false;//是否第一次渲染树形菜单
    var master_form = {};
    var setting={//树设置
        identValueSetting:{//区划树设置
            edit: {
                enable: true,
                showRemoveBtn: false,
                showRenameBtn: false,
                drag: {
                    isCopy: true,
                    isMove: false,
                    prev: false,
                    next: false,
                    inner: false
                }
            },
            data: {
                key: {
                    children: "sub",
                    isParent: "isParent",
                    title: "name"
                },
                simpleData: {
                    enable: true
                }
            },
            callback: {
                onExpand: onExpandIdentValueTree,
                onClick: identValueOnClick
            },
            view: {
                showIcon: true,
                showLine: true
            }
        },
    }
    var parentId = {};
    var reportData;
    var microData;
    var raw_data;
    var table_data;
    var masterList = [];
    var formList = [];
    //获取权限方法
    if(userInfo){
        var access_token = localStorage.getExpire("access_token");
        var token_type = localStorage.getExpire("token_type");
        Authorization = token_type+" "+access_token;
        getTemplateIdenPower();
        getTemplateIdenManageTablePower();
        getIdentValuePower();
        initIdenGroupTree();
        // var dataarr = [{"data_type":0,
        //     "id":"root",
        //     "name":"根目录",
        //     "par_id":"",
        //     "version":"0",
        //     "sub":[]
        // }];
        // $.fn.zTree.init($("#treeTbTree"), setting.identValueSetting, dataarr);
        // parentId = resArr[0]
        // first_renderTree = true;
        // getTableData(resArr[0].id,{})
        // getTreeTable({},function (resArr) {
        //     var dataarr = [{"data_type":0,
        //         "id":"root",
        //         "name":"根目录",
        //         "par_id":"",
        //         "version":"0",
        //         "sub":[]
        //     }];
        //     $.fn.zTree.init($("#treeTbTree"), setting.identValueSetting, dataarr);
        //     parentId = resArr[0]
        //     first_renderTree = true;
        //     getTableData(resArr[0].id,{})
        // });
        getMicroType();
        getReportType();
    }
    // 打开新增指标模板弹窗
    $('#addTemplateIdenBtn').click(function () {
        showTemplateIdenModel();
    });
    // 打开编辑指标模板弹窗
    $('#editTemplateIdenBtn').click(function () {
        if(parentId.id =="root"){
            layer.msg('根目录不允许编辑', {icon: 2});
        }else{
            showEditIndexMenuModel(parentId);
        }
    });
    //删除指标模板
    $('#deleteTemplateIdenBtn').click(function () {
        if(!parentId.id){
            layer.msg("请选择需要删除的目录", {icon: 2});
            return false
        }
        if(parentId.id =="root"){
            layer.msg('根目录不允许删除', {icon: 2});
        }else{
            showDeleteTemplateIdenModel(parentId);
        }

    });

    // 指标管理搜索按钮点击事件
    form.on('submit(formSubSearchTbLtrt)', function (data) {
        let obj = {
            metaName:data.field.keyword
        }
        fistRenderPage = true
        getTableData(parentId.id,obj)
        });
    //更多筛选点击
    $('#morefilter-btn-idenManage').click(function () {
        openMoreFilterModel();
        return false;
    })

    // 指标管理更多筛选
    form.on('submit(idenMoreFilterForm)', function (data) {
        var obj = {
            metaName:data.field.name,
            meta_type:data.field.meta_type,
            report_type:data.field.report_type
        }
        getTableData(parentId.id,obj)
        $("#idenMoreFilterModel").slideUp();
        return false;
    });
    $("#closeIdenMoreFilterModel").click(function () {
        $("#idenMoreFilterModel").slideUp();
    });
    $(".layui-fluid .layui-card").click(function (node) {
        if(!(document.getElementById("idenMoreFilterModel").contains(node.target))){
            $("#idenMoreFilterModel").slideUp();
        }
    });

    $('#add-btn-template-idenManage').click(function () {
        openAddIdenManage();
    });
    $('#import-btn-template-idenManage').click(function () {
        openImportIdenManage();
    })

    // 表格工具条点击事件
    table.on('tool(identGroupTable)', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        if (layEvent === 'edit') { // 修改
            showTdenManageEditModel(data);
        } else if (layEvent === 'delete') { // 删除
            showIndexClassDeleteModel(data);
        } else if(layEvent === 'setMasterSlaveClass'){//设置主从表
            showSetMasterSlaveClassModel(data);
        } else if(layEvent === 'setCatalog'){//设置目录
            showSetCatalogModel(data);
        } else if(layEvent === 'idenManage'){//指标管理
            showIdenManageModel(data);
        } else if(layEvent === 'dataManage'){//数据管理
            showDataManageModel(data);
        }
    });

    function initIdenGroupTree(){
        var dataarr = [{"data_type":0,
            "id":"root",
            "name":"根目录",
            "par_id":"",
            "version":"0",
            "sub":[]
        }];
        $.fn.zTree.init($("#treeTbTree"), setting.identValueSetting, dataarr);
        parentId = dataarr[0]
        first_renderTree = true;
        getTableData(dataarr[0].id,{})
    }

    /*渲染数据表管理权限*/
    function getTemplateIdenPower() {
        var str = template("template-idenManage-tmpl",{});
        document.getElementById("template-idenManage-tmpl-box").innerHTML = str;
    }
    /*渲染数据表表格里的权限*/
    function getTemplateIdenManageTablePower() {
        var str = template("ident-template-idenManage-tmp",{});
        document.getElementById("ident-template-idenManage-box").innerHTML = str;
    }

    /*渲染指标模板权限*/
    function getIdentValuePower() {
        var str = template("template-iden-tmpl",{});
        document.getElementById("template-iden-tmpl-box").innerHTML = str;
    }

    //获取树形目录的值
    function getTreeTable(obj,callback) {
        let parent_id = obj.id?obj.id:'root';
        axios({
            method: 'get',
            url:microUrl.microObject.microMenu.microMenuList+'/'+ parent_id + '/',
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var data = response.data.data;
                    var resArr = [];
                    zhuanHuanTree(data,resArr);
                    // IdentValueTree = resArr;
                    callback(resArr)

                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });
    }
    //转换菜单集合数据
    function zhuanHuanTree(tdata,resData) {
        if(Array.isArray(tdata) && tdata.length>0){
            tdata.forEach(function(v,i){
                var newValue=v.name;
                resData[i]=v;
                resData[i].title=newValue;
                resData[i].icon = "";
                resData[i].isParent = "true";
                resData[i].sub = [];
            });
        }
    }

    //查询下方区划树的下级区划值（懒加载）
    function onExpandIdentValueTree(event, treeId, treeNode) {

        if(treeNode.sub.length>0||treeNode.hasChild=='0'){
            return false
        }
        getTreeTable(treeNode,function (resArr) {
            const treeObj = $.fn.zTree.getZTreeObj("treeTbTree");
            treeNode = treeObj.addNodes(treeNode,resArr);


        });
    }
    //选中分组值
    function identValueOnClick(event, treeId, treeNode){
        parentId = treeNode;
        first_renderTree = false;
        fistRenderPage = true
        getTableData(treeNode.id,{})
    }
    //获取表数据
    function getTableData(menuId,mircoObj) {
        var req={
            current: current,
            size: pageSize,
            name:mircoObj.metaName?mircoObj.metaName:'',
            menu_id:menuId,
            meta_type:mircoObj.meta_type?mircoObj.meta_type:'',
            report_type:mircoObj.report_type?mircoObj.report_type:'',
        };
        axios.get(microUrl.microObject.microList.microDataList,{
            params: req,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var data = response.data.data;                    
                    table_data = data
                    renderTable(data)
                }
            })
            .catch(function (error) {
                console.log(error)
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });
    }
    //获取数据表分类
    function getMicroType(){
        axios({
            method: 'get',
            url:microUrl.microObject.microList.microType,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var data = response.data.data;
                    microData = data
                    var str = template("template-microType-tmpl",{microData});
                    document.getElementById("micro-type").innerHTML = str;
                    form.render('select')
                    // IdentValueTree = resArr;
                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });
    }
    //获取报告期类型
    function getReportType() {
        axios({
            method: 'get',
            url:microUrl.microObject.microList.microReportType,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var data = response.data.data;
                    reportData = data
                    var str = template("template-reportType-tmpl",{reportData});
                    document.getElementById("report-type").innerHTML = str;
                    form.render('select')
                    // IdentValueTree = resArr;
                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });
    }
    /*渲染指标管理表格*/
    function renderTable(micro_data) {
        table.render({
            elem: '#identGroupTable',
            size: 'sm', //小尺寸的表格
            // skin:'nob',
            data: micro_data.records,
            page: false,
            cellMinWidth: 100,
            cols: [[
                {type:'numbers', title: '#'},
                {field: 'name', align: 'center', title: '表名'},
                {field: 'metaTypeName', align: 'center', title: '表分类'},
                {field: 'reportTypeName', align: 'center', title: '报告期类型'},
                {field: 'parentTableName', align: 'center', title: '主表'},
                {field: 'startTime', align: 'center', title: '开始时间'},
                {field: 'endTime', align: 'center', title: '结束时间'},
                {field: 'localeOfSubmission', align: 'center', title: '地点'},
                {field: 'datavIsMulti', align: 'center', title: '多版本数据导入',templet:function (d) {
                        return d.datavIsMulti?"是":"否"
                    }},
                {align: 'center', toolbar: '#ident-template-idenManage-box',fixed:'right', title: '操作', minWidth: 500}
            ]]
        });

        //第一次才渲染分页
        if(fistRenderPage){
            laypage.render({
                elem: 'page-box'
                ,count: micro_data.total,
                limit:micro_data.size,
                groups:1,
                current:current
                ,layout: ['count','prev','page', 'next']
                ,jump: function(obj, first){
                    if(!first){
                        current = obj.curr;
                        fistRenderPage = false;
                        getTableData(parentId.id,{});
                    }
                }
            });
        }
    }

    /*显示新增指标模板弹窗*/
    function showTemplateIdenModel(obj) {
        if(first_renderTree){
            parentId = {}
            first_renderTree = false;
        }
        window.mSelUser = {
            parent_id:parentId.id?parentId.id:'root',
            menuName:parentId.name?parentId.name:'根目录'
        };  // 传递数据到表单页面，也可以使用top.xxx

        admin.open({
            title: '新增明细对象目录',
            url: 'index/addIndexMenu.html',
            end: function () {
                initIdenGroupTree();
                // getTreeTable({},function (resArr) {
                //     $.fn.zTree.init($("#treeTbTree"), setting.identValueSetting, resArr);
                //     getTableData(resArr[0].id,{})
                //     first_renderTree = true;
                //     parentId = resArr[0]
                // });
            },
            success: function (layero, dIndex) {
                // 弹窗超出范围不出现滚动条
                $(layero).children('.layui-layer-content').css('overflow', 'visible');
            }
        });
    }
    /*显示编辑对象目录弹窗*/
    function showEditIndexMenuModel() {
        if(!parentId.id){
            layer.msg('请选择需要编辑的目录', {icon: 2});
            return false
        }
        window.mSelUser = {
            menuData:parentId
        };  // 传递数据到表单页面，也可以使用top.xxx
        window.editIdentGroupStatus = false;

        admin.open({
            title: '编辑明细对象目录',
            url: 'index/editIndexMenu.html',
            end: function () {
                if(window.editIdentGroupStatus){
                    initIdenGroupTree();
                }
            },
            success: function (layero, dIndex) {
                // 弹窗超出范围不出现滚动条
                $(layero).children('.layui-layer-content').css('overflow', 'visible');
            }
        });
    }

    /*显示删除指标模板弹窗*/
    function showDeleteTemplateIdenModel(obj) {
        layer.confirm('确定将永久删除目录“'+obj.name+'”吗？', {
            skin: 'layui-layer-admin',
            shade: .1
        }, function (i) {
            layer.close(i);
            layer.load(2);
            axios({
                method: 'delete',
                url:microUrl.microObject.microMenu.deleteMicroMenu + obj.id,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (res) {
                    if (res.status == 200&&res.data.message=="success") {
                        layer.closeAll('loading');
                        layer.msg("删除成功", {icon: 1});
                        initIdenGroupTree();
                    } else {
                        layer.msg(res.data.message, {icon: 2});
                        layer.closeAll('loading');
                    }
                })
                .catch(function (error) {
                    console.log(error);
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                })
        });
    }

    /*显示编辑指标管理弹窗*/
    function showTdenManageEditModel(data) {
        window.mSelUser = {
            micro_data:data,
            parent_id:parentId.id?parentId.id:'root',
            menuName:parentId.name,
            meta_type:microData,
            report_type:reportData,
        };  // 传递数据到表单页面，也可以使用top.xxx
        admin.open({
            title: '编辑数据表',
            url: 'index/editIndexClass.html',
            area: ['400px', '700px'],
            end: function () {                
                getTableData(parentId.id,{})
            },
            success: function (layero, dIndex) {
                // 弹窗超出范围不出现滚动条
                $(layero).children('.layui-layer-content').css('overflow', 'visible');
            }
        });

    }

    /*显示删除指标弹窗*/
    function showIndexClassDeleteModel(data) {
        layer.confirm('确认删除数据表：'+data.name+'吗？', {
            skin: 'layui-layer-admin',
            size:'sm',
            shade: .1
        }, function (i) {
            layer.close(i);
            layer.load(2);
            axios({
                method: 'delete',
                url:microUrl.microObject.microList.deleteMicroList + data.id,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (res) {
                    if (res.status == 200&&res.data.message=="success") {
                        fistRenderPage = true
                        layer.closeAll('loading');
                        layer.msg("删除成功", {icon: 1});
                        getTableData(parentId.id,{})
                    } else {
                        layer.msg(res.data.message, {icon: 2});
                        layer.closeAll('loading');
                    }
                })
                .catch(function (error) {
                    console.log(error);
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                })
        });
    }

    /*显示更多筛选框*/
    function openMoreFilterModel() {
        $("#idenMoreFilterModel").slideDown();
    }
    /*显示新增数据表弹窗*/
    function openAddIdenManage() {
        if(parentId.id=="root"){
            layer.msg("根目录不能添加表,请先选择正确的目录", {icon: 2});
            return;
        }else{
            window.mSelUser = {
                parent_id:parentId.id?parentId.id:'root',
                menuName:parentId.name,
                meta_type:microData,
                report_type:reportData
            };  // 传递数据到表单页面，也可以使用top.xxx
            admin.open({
                title: '新增数据表',
                url: 'index/addIndexClass.html',
                end: function () {
                    fistRenderPage = true
                    getTableData(parentId.id,{});
                },
                success: function (layero, dIndex) {
                    // 弹窗超出范围不出现滚动条
                    $(layero).children('.layui-layer-content').css('overflow', 'visible');
                }
            });
        }
    }

    /*显示导入指标弹窗*/
    function openImportIdenManage() {
        layui.use(['admin','table'], function () {
            var $ = layui.jquery;
            var admin = layui.admin;
            var form = layui.form;
            var table = layui.table;

            admin.open({
                title: '导入指标',
                url: 'template/importIden.html',
                end: function () {

                },
                success: function (layero, dIndex) {
                    // 弹窗超出范围不出现滚动条
                    $(layero).children('.layui-layer-content').css('overflow', 'visible');
                }
            });
        })
    }

    /*显示设置主从表弹窗*/
    function showSetMasterSlaveClassModel(data) {
        /*渲染分组表格里的权限*/
        var str = template("ident-master-tmp",{});
        document.getElementById("ident-master-tpl-box").innerHTML = str;
        var newstr = template("ident-form-tmp",{});
        document.getElementById("ident-form-tpl-box").innerHTML = newstr;
        layui.use(['admin','table'], function () {
            var formSelects = layui.formSelects;
            var $ = layui.jquery;
            var admin = layui.admin;
            var form = layui.form;
            var table = layui.table;
            // window.mSelUser = {
            //     pmIden:table_data,
            //     current_data:data
            // };  // 传递数据到表单页面，也可以使用top.xxx
            admin.open({
                type: 1,
                title: '设置主从表',
                offset: "auto",
                area: ['900px', '600px'],
                content: $('#setMasterSlaveClassModel').html(),
                success: function (layero, dIndex) {
                    getSelectIden({value:data.id},function (pmIdenMicro) {
                        formList = pmIdenMicro

                        if(data.parid === 'root' || !data.parid){
                        }else {
                            let form_box = data.cmIdenCodes.split(',');
                            let form_index = 0;
                            for(let i = 0;i<form_box.length;i++){
                                for(let j = 0;j<formList.length;j++){
                                    if(form_box[i] == formList[j].idenCode){
                                        formList[j].form = form_index + 1;
                                        form_index += 1;
                                    }
                                }
                            }
                            renderFormTable(objSort(formList,'form'))
                        }
                        form.render('checkbox');
                    })
                    var req={
                        current: 1,
                        size: 100,
                        menu_id:parentId.id,
                    };
                    axios.get(microUrl.microObject.microList.microDataList,{
                        params: req,
                        headers:{
                            'Authorization':Authorization
                        }
                    })
                        .then(function (response) {
                            if(response.status == 200 &&response.data.message == "success"){
                                var pmData = response.data.data;
                                let pmIdenLis = $.extend(true, [],pmData.records);
                                for(let i = 0; i<pmIdenLis.length;i++){
                                    if(pmIdenLis[i].id == data.id){
                                        pmIdenLis.splice(i,1);
                                    }
                                }
                                var str = template("template-pmIden-tmpl",{pmIdenLis});
                                document.getElementById("pmIden").innerHTML = str;
                                form.render('select');
                                if(data.parid == 'root' || !data.parid){

                                }else {
                                    getSelectIden({value:data.parid},function (pmIdenMicro) {

                                        masterList = pmIdenMicro
                                        let master_box = data.pmIdenCodes.split(',');
                                        let master_index = 0;
                                        for(let i = 0;i<master_box.length;i++){
                                            for(let j = 0;j<masterList.length;j++){
                                                if(master_box[i] == masterList[j].idenCode){
                                                    masterList[j].master = master_index + 1;
                                                    master_index += 1;
                                                }
                                            }
                                        }
                                        renderMasterTable(objSort(masterList,'master'))
                                    })
                                }
                                form.val('versionGroupForm',data);  // 回显数据
                            }
                        })
                        .catch(function (error) {
                            console.log(error)
                            if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                                // 进行重新登陆
                                localStorage.clear();
                                top.location.href=loginPageUrl;
                            }
                        });

                    form.on('select(pmIden)', function(pmIdenlist){
                        console.log('data:',data)
                        console.log('pmIdenlist:',pmIdenlist)
                        if(pmIdenlist.value!=""){
                            getSelectIden(pmIdenlist,function (pmIdenMicro) {
                                masterList = pmIdenMicro
                                for(let i = 0;i<formList.length;i++){
                                    formList[i].form = ""
                                }
                                console.log('formList:',formList)
                                console.log('pmIdenMicro:',pmIdenMicro)
                                renderFormTable(formList)
                                renderMasterTable(pmIdenMicro)
                            })
                        }else{
                            renderFormTable([])
                            renderMasterTable([])
                        }
                    });
                    form.on('submit(setPmIden)', function (current_data) {
                        //执行实例
                        let cmIden_box = [];
                        let pmIden_box = [];
                        for(let i = 0;i<objSort(formList,'form').length;i++){
                            if(objSort(formList,'form')[i].form){
                                cmIden_box.push(objSort(formList,'form')[i].idenCode)
                            }
                        }

                        for(let i = 0;i<objSort(masterList,'master').length;i++){
                            if(objSort(masterList,'master')[i].master){
                                pmIden_box.push(objSort(masterList,'master')[i].idenCode)
                            }
                        }
                        if(cmIden_box.length==pmIden_box.length){
                            let cmIdenCodes = "";
                            let pmIdenCodes = "";
                            cmIdenCodes += cmIden_box.map(function (item) {
                                return item
                            }).join(',')
                            pmIdenCodes += pmIden_box.map(function (item) {
                                return item
                            }).join(',')
                            let form_data = {
                                id:data.id,
                                parid:current_data.field.parid,
                                version:data.version,
                                cm_iden_codes:cmIdenCodes,
                                pm_iden_codes:pmIdenCodes
                            }
                            axios({
                                method: 'put',
                                data:$.param(form_data),
                                url:microUrl.microObject.microList.parentTable,
                                headers:{
                                    'Authorization':Authorization
                                }
                            })
                                .then(function (res) {
                                    if (res.status == 200&&res.data.message=="success") {
                                        layer.closeAll('loading');
                                        layer.msg("设置成功", {icon: 1});
                                    } else {
                                        layer.msg(res.data.message, {icon: 2});
                                        layer.closeAll('loading');

                                    }
                                    layer.close(dIndex);
                                    getTableData(parentId.id,{});
                                })
                                .catch(function (error) {
                                    console.log(error);
                                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                                        // 进行重新登陆
                                        localStorage.clear();
                                        top.location.href=loginPageUrl;
                                    }
                                })
                            return false;
                        }else {
                            layer.msg("主表指标需保持和从表指标的数量一致", {icon: 2});
                        }
                        return false;
                    });
                }
            });
        })
    }
    //渲染主表表格
    function renderMasterTable(pmIdenMicro) {
        table.render({
            elem: '#master_table',
            size: 'sm', //小尺寸的表格
            // skin:'nob',
            data:pmIdenMicro,
            page: false,
            cellMinWidth: 100,
            done:function(){
              for(let i = 0;i<masterList.length;i++){
                  if(masterList[i].master){
                      $($(".masterTable").find("tr")[masterList[i].master]).css({'background':'#00a0e9','color':'#fff'})
                  }
              }
            },
            cols: [[
                {type:'numbers', title: '#'},
                {field: 'idenName', align: 'center', title: '指标名称'},
                {align: 'center', toolbar: '#ident-master-tpl-box', title: '操作'}
            ]],
        });

        $(".masterTable").find("tr").click(function () {
            $(this).addClass('check_tr').siblings().removeClass('check_tr')
        })
    }

    //监听行单击事件
    table.on('row(master_table)', function(obj){
        if(!obj.data.master){
            master_form.master = obj.data.id
        }else {
            console.log(obj.data)
        }
    });
    // 表格工具条点击事件
    table.on('tool(master_table)', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        if(layEvent === 'delete'){
            for(let i = 0;i<masterList.length;i++){
                if(data.id == masterList[i].id){
                    masterList.splice(i,1)
                }
            }
            if(data.master){
                for(let i = 0;i<formList.length;i++){
                    if(data.master == formList[i].form){
                        formList[i].form = "";
                    }
                }
                renderFormTable(objSort(formList,'form'))
            }
            renderMasterTable(objSort(masterList,'master'))

        }
    });
    //从表点击确认
    // 表格工具条点击事件
    table.on('tool(form_table)', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        if (layEvent === 'confirm') { // 确认
            if(master_form.master){
                master_form.form = data.id
                for (let i = 0;i<masterList.length;i++){
                    if(masterList[i].id == master_form.master){
                        let masterArr = [];
                        $.each(masterList,function (index,item) {
                            if(item.master){
                                masterArr.push(item.master)
                            }
                        })
                        let newArr = masterArr.sort((a,b)=>{
                            return a-b;   //sort方法使数组排序，顺序为升序
                        })
                        let prevPage = newArr[newArr.length-1]?newArr[newArr.length-1]:0
                        masterList[i].master = prevPage + 1;
                    }
                }
                for (let i = 0;i<formList.length;i++){
                    if(formList[i].id == master_form.form){
                        let formArr = [];
                        $.each(formList,function (index,item) {
                            if(item.form){
                                formArr.push(item.form)
                            }
                        })
                        let newArr = formArr.sort((a,b)=>{
                            return a-b;   //sort方法使数组排序，顺序为升序
                        })

                        let prevPage = newArr[newArr.length-1]?newArr[newArr.length-1]:0
                        formList[i].form = prevPage + 1;
                    }
                }
                master_form = {}
                renderMasterTable(objSort(masterList,'master'))
                renderFormTable(objSort(formList,'form'))
            }else {
                layer.msg("请先选择主表内容", {icon: 2});
            }
        }else if(layEvent === 'delete'){
            for(let i = 0;i<formList.length;i++){
                if(data.id == formList[i].id){
                    formList.splice(i,1)
                }
            }
            if(data.form){
                for(let i = 0;i<masterList.length;i++){

                    if(data.form == masterList[i].master){
                        masterList[i].master = "";
                    }
                }
                renderMasterTable(objSort(masterList,'master'))
            }

            renderFormTable(objSort(formList,'form'))
        }else if(layEvent === 'cancel'){
            for(let i = 0;i<formList.length;i++){
                if(data.id == formList[i].id){
                    formList[i].form = ""
                }
            }
            if(data.form){
                for(let i = 0;i<masterList.length;i++){

                    if(data.form == masterList[i].master){
                        masterList[i].master = "";
                    }
                }
                renderMasterTable(objSort(masterList,'master'))
            }

            renderFormTable(objSort(formList,'form'))
        }
    });
    //通过定义的字段对原数组进行排序
    function objSort(arr,arr_key){
        let sort_arr = [];
        let other_arr = [];
        for(let i = 0;i<arr.length;i++){
            if(arr[i][arr_key]){
                sort_arr.push(arr[i])
            }else {
                other_arr.push(arr[i])
            }
        }

        sort_arr.sort((a,b)=>{ return a[arr_key]-b[arr_key]})//升序
        for(let i = 0;i<sort_arr.length;i++){
            sort_arr[i][arr_key] = i+1
        }
        let newArr = sort_arr.concat(other_arr)
        return newArr
    }
    //渲染从表表格
    function renderFormTable(pmIdenMicro) {
        table.render({
            elem: '#form_table',
            size: 'sm', //小尺寸的表格
            // skin:'nob',
            data:pmIdenMicro,
            page: false,
            cellMinWidth: 100,
            done:function(){
                for(let i = 0;i<formList.length;i++){
                    if(formList[i].form){
                        $($(".fromTable").find("tr")[formList[i].form]).css({'background':'#00a0e9','color':'#fff'})
                    }
                }
            },
            cols: [[
                {type:'numbers', title: '#'},
                {field: 'idenName', align: 'center', title: '指标名称'},
                {align: 'center', title: '操作',templet:function (d) {
                        if(d.form){
                            return `<a class="layui-btn layui-btn-xs layui-btn-warning" lay-event="cancel">取消</a>
                                <a class="layui-btn layui-btn-danger layui-btn-xs micro-ident-group-delete" lay-event="delete">删除</a>`
                        }else {
                            return `<a class="layui-btn layui-btn-xs layui-btn-primary " lay-event="confirm" >确定</a>
                                <a class="layui-btn layui-btn-danger layui-btn-xs micro-ident-group-delete" lay-event="delete">删除</a>`
                        }

                    }}
            ]]
        });
    }
    //获取指标
    function getSelectIden(pmIdenlist,callback) {
        var req={
            current: 1,
            size: 100,
            miid:pmIdenlist.value
        };
        axios.get(microUrl.microObject.idenMicroMeta.idenMicroList,{
            params: req,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var data = response.data.data;
                    var pmIdenMicro = data.records;
                    callback(pmIdenMicro)
                }
            })
            .catch(function (error) {
                console.log(error)
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });
    }
    /*显示设置目录弹窗*/
    function showSetCatalogModel(data) {
        layui.use(['admin','table'], function () {
            var $ = layui.jquery;
            var admin = layui.admin;
            var form = layui.form;
            var table = layui.table;
            window.mSelUser = {
                menuData:data
            };  // 传递数据到表单页面，也可以使用top.xxx
            admin.open({
                title: '设置目录',
                url: 'index/setCatalog.html',
                area:['500px','400px'],
                end: function () {

                },
                success: function (layero, dIndex) {
                    // 弹窗超出范围不出现滚动条
                    $(layero).children('.layui-layer-content').css('overflow', 'visible');
                }
            });
        })
    }

    /*显示指标管理页面*/
    function showIdenManageModel(data) {
        layui.use(['admin','table'], function () {
            var $ = layui.jquery;
            var admin = layui.admin;
            var form = layui.form;
            var table = layui.table;
            window.mSelUser = {
                miid:data.id
            };  // 传递数据到表单页面，也可以使用top.xxx
            admin.popupRight({
                title: false, //不显示标题栏
                url: 'idenManage.html',
                offset: 'rt',
                area:['80vw;','calc(100vh - 30px)'],
                closeBtn: true,
                end: function () {

                },
                success: function (layero, dIndex) {
                    // 弹窗超出范围不出现滚动条
                    $(layero).children('.layui-layer-content').css('overflow', 'visible');
                }
            });
        })
    }

    /*显示数据管理页面*/
    function showDataManageModel(data) {
        layui.use(['admin','table'], function () {
            var $ = layui.jquery;
            var admin = layui.admin;
            var form = layui.form;
            var table = layui.table;
            window.mSelUser = {
                miid:data
            };  // 传递数据到表单页面，也可以使用top.xxx
            admin.popupRight({
                title: false, //不显示标题栏
                url: 'dataManage.html',
                offset: 'rt',
                area:['80vw;','calc(100vh - 30px)'],
                closeBtn: true,
                end: function () {

                },
                success: function (layero, dIndex) {
                    // 弹窗超出范围不出现滚动条
                    $(layero).children('.layui-layer-content').css('overflow', 'visible');
                }
            });
        })
    }
});


